<template>
  <div class="home">
    <div class="menu">
      <div>
        <el-dropdown @command="handleClick">
          <img :src="currentUser.avatar" style="cursor: pointer" class="avatar">
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="editAvatar">更换头像</el-dropdown-item>
            <el-dropdown-item command="editNickname">修改昵称</el-dropdown-item>
            <el-dropdown-item command="editPassword">修改密码</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <div class="menu-item" title="聊天">
          <el-badge :value="unreadMsgSum" :hidden="unreadMsgSum === 0 ? true : false">
            <div :class="selectedItem == 0 ? 'menu-item-active '+'iconfont icon-message' : 'iconfont icon-message'" @click="navigate('/home/chat',0)"></div>
          </el-badge>
        </div>
        <div class="menu-item" title="通讯录">
          <el-badge :value="friendRequestMsgSum" :hidden="friendRequestMsgSum === 0 ? true : false">
            <div :class="selectedItem == 1 ? 'menu-item-active '+'iconfont icon-user-list' : 'iconfont icon-user-list'" @click="navigate('/home/user',1)"></div>
          </el-badge>
        </div>
        <div class="menu-item" title="收藏">
          <div :class="selectedItem == 2 ? 'menu-item-active '+'iconfont icon-collection' : 'iconfont icon-collection'" @click="navigate('/home/face',2)"></div>
        </div>
        <div class="menu-item" title="聊天文件">
          <div :class="selectedItem == 3 ? 'menu-item-active '+'iconfont icon-file' : 'iconfont icon-file'" @click="navigate('/home/editor',3)"></div>
        </div>
        <div class="menu-item" title="朋友圈">
          <el-badge :value="momentMsgSum" :hidden="momentMsgSum === 0 ? true : false">
            <div :class="selectedItem == 4 ? 'menu-item-active '+'iconfont icon-moment' : 'iconfont icon-moment'" @click="navigate('/home/moment',4)"></div>
          </el-badge>
        </div>
      </div>
      <div>
        <div class="menu-item" title="小程序">
          <div :class="selectedItem == 5 ? 'menu-item-active '+'iconfont icon-program' : 'iconfont icon-program'" @click="navigate('/home/emoji',5)"></div>
        </div>
        <div class="menu-item" title="手机">
          <div :class="selectedItem == 6 ? 'menu-item-active '+'iconfont icon-phone' : 'iconfont icon-phone'" @click="navigate('/home/background',6)"></div>
        </div>
        <div class="menu-item" title="更多">
          <div :class="selectedItem == 7 ? 'menu-item-active '+'iconfont icon-more' : 'iconfont icon-more'" @click="navigate('/home/audio',7)"></div>
        </div>
      </div>
    </div>
    <div class="container">
      <router-view></router-view>
    </div>
    <el-dialog title="修改密码" :visible.sync="editPasswordDialogVisible" width="400px">
      <el-form :model="passwordForm" ref="form" :rules="passwordRules" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword" style="margin-bottom: 20px">
          <el-input v-model="passwordForm.oldPassword" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword" style="margin-bottom: 20px">
          <el-input v-model="passwordForm.newPassword" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" style="margin-bottom: 20px">
          <el-input v-model="passwordForm.confirmPassword" show-password></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="emailCode">
          <el-input  class="input-item" v-model="passwordForm.emailCode" placeholder="验证码">
            <template slot="append">
              <el-button v-if="code.status === 0" @click="getEmailCode">获取验证码</el-button>
              <el-button v-if="code.status === 1" disabled>
                获取<i class="el-icon-loading"></i>
              </el-button>
              <el-button v-if="code.status === 2" disabled>
                {{code.countDown}}秒后重新获取
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitForm('form')" size="mini">提交</el-button>
        <el-button @click="editPasswordDialogVisible = false" size="mini">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="更换头像" :visible.sync="editAvatarDialogVisible" width="400px">
      <div style="display: flex;justify-content: space-around">
        <div style="position: relative;width: 180px;height: 180px;" @mouseover="showDelete" @mouseout="hideDelete">
          <!--头像-->
          <img :src="url" width="180px" height="180px">
          <!--上传头像-->
          <div v-show="deleteVisible" style="display:flex;justify-content: space-around;align-items: center;
    position: absolute;top: 0; left: 0;right: 0;bottom: 0;z-index: 10;background-color: rgba(0,0,0,.5)">
            <i class="el-icon-edit-outline" style="font-size: 40px;color: white;cursor: pointer;" @click="showClipPicture" title="更换"></i>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="success" @click="updateAvatar()" size="mini">提交</el-button>
        <el-button @click="cancelUpdate()" size="mini">取消</el-button>
      </div>
    </el-dialog>
    <clip-picture v-if="clipPictureVisible" @getUrl="getAvatarUrl"></clip-picture>
  </div>
</template>

<script>
import ClipPicture from '../components/ClipPicture'
export default {
  name: 'Home',
  data () {
    return {
      clipPictureVisible: false,
      token: '',
      currentUser: {},
      editAvatarDialogVisible: false,
      editPasswordDialogVisible: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
        emailCode: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        emailCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9~`!@#$%^&*()\-_=+[\]{}|;:'",.<>/?]+$/, message: '密码只能包含英文字母、数字和标点符号', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      },
      deleteVisible: false,
      url: '',
      processing: false,
      code: {
        status: 0,
        countDown: 0,
        timer: null
      }
    }
  },
  mounted () {
    this.currentUser = this.$store.state.currentUser
    this.getUsers()
    this.navigate('/home/chat', 0)
  },
  components: {
    ClipPicture
  },
  beforeDestroy () {},
  methods: {
    cancelUpDate () {
      this.editAvatarDialogVisible = false
      this.deleteAvatar(this.url)
    },
    showClipPicture () {
      // 删除已选图像
      if (this.url !== '') {
        this.deleteAvatar(this.url)
      }
      if (this.clipPictureVisible === true) {
        this.clipPictureVisible = false
        setTimeout(() => {
          this.clipPictureVisible = true
        }, 500)
      } else {
        this.clipPictureVisible = true
      }
    },
    getAvatarUrl (url) {
      this.url = url
      this.clipPictureVisible = false
      this.editAvatarDialogVisible = true
    },
    getUsers () {
      this.axios.get(`/api/v1/friend/list?userId=${this.currentUser.id}`).then((response) => {
        if (response.data.code === 1) {
          let users = response.data.data
          this.$store.commit('setUsers', users)
        } else {
          this.$message.error(response.data.message)
        }
      }).catch((error) => {
        this.$message.error(error)
        console.log(error)
      })
    },
    navigate (path, item) {
      this.$store.commit('setSelectedItem', item)
      this.$router.push(path)
    },
    validateConfirmPassword (rule, value, callback) {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    handleClick (type) {
      if (type === 'logout') {
        this.$confirm('确定退出登录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.logout()
        }).catch(() => {
        })
      } else if (type === 'editPassword') {
        this.editPasswordDialogVisible = true
      } else if (type === 'editAvatar') {
        this.showClipPicture()
      } else if (type === 'editNickname') {
        this.$prompt('', '修改昵称', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: this.currentUser.nickname
        }).then(({ value }) => {
          this.updateNickname(value)
        }).catch(() => {
        })
      }
    },
    logout () {
      this.axios.post('/api/v1/user/logout').then((response) => {
        if (response.data.code === 1) {
          this.$store.commit('setCurrentUser', null)
          localStorage.removeItem('token')
          this.$router.push('/')
          let socket = this.$store.state.socket
          socket.close()
        } else {
          this.$message.error(response.data.message)
        }
      }).catch((error) => {
        this.$message({
          message: error,
          type: 'error'
        })
        console.log(error)
      })
    },
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = new URLSearchParams()
          params.append('newPassword', this.passwordForm.newPassword)
          params.append('oldPassword', this.passwordForm.oldPassword)
          params.append('id', this.currentUser.id)
          this.axios.post('/api/v1/user/edit/password', params).then((response) => {
            if (response.data.code === 1) {
              this.editPasswordDialogVisible = false
              this.$alert('修改密码成功,请重新登录!', '提示', {
                confirmButtonText: '重新登录',
                type: 'info',
                center: true,
                callback: action => {
                  this.$router.push('/')
                }
              })
            } else {
              this.$message({
                message: response.data.message,
                type: 'error'
              })
            }
          }).catch((error) => {
            this.$message({
              message: error,
              type: 'error'
            })
            console.log(error)
          })
        }
      })
    },
    updateNickname (nickname) {
      let params = new URLSearchParams()
      params.append('nickname', nickname)
      params.append('id', this.currentUser.id)
      this.axios.post('/api/v1/user/edit/avatar', params).then((response) => {
        if (response.data.code === 1) {
          this.currentUser.nickname = nickname
          this.$store.commit('setCurrentUser', this.currentUser)
          this.$message.success('修改成功！')
        } else {
          this.$message({
            message: response.data.message,
            type: 'error'
          })
        }
      }).catch((error) => {
        this.$message({
          message: error,
          type: 'error'
        })
        console.log(error)
      })
    },
    showDelete () {
      this.deleteVisible = true
    },
    hideDelete () {
      this.deleteVisible = false
    },
    // 根据url删除头像
    deleteAvatar (url) {
      const formData = new FormData()
      formData.append('fileName', url)
      this.axios.post('/api/v1/file/delete', formData, {
        headers: {
          'Content-type': 'multipart/form-data'
        }
      }).then((response) => {
        if (response.data.code === 1) {
        } else {
          this.$message.error(response.data.message)
        }
      }).catch((error) => {
        this.$message.info('服务器繁忙!')
        console.error('error ' + error)
      })
    },
    // 更新用户头像
    updateAvatar () {
      let params = new URLSearchParams()
      params.append('avatar', this.url)
      params.append('id', this.currentUser.id)
      this.axios.post('/api/v1/user/edit/avatar', params).then((response) => {
        if (response.data.code === 1) {
          // 更新完成后删除头像
          this.deleteAvatar(this.currentUser.avatar)
          // 删除头像后，更新本地用户头像
          this.currentUser.avatar = this.url
          this.currentUser.avatarThumb = this.url
          this.editAvatarDialogVisible = false
        } else {
          this.$message({
            message: response.data.message,
            type: 'error'
          })
        }
      }).catch((error) => {
        this.$message({
          message: error,
          type: 'error'
        })
        console.log(error)
      })
    },
    getEmailCode () {
      let email = this.ruleForm.email
      console.log('email = ' + email)
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (emailRegex.test(email)) {
        this.code.status = 1
        this.axios.get(`/api/v1/mail/verify_code?email=${email}`).then((response) => {
          if (response.data.code === 1) {
            this.code.status = 2
            this.$message.success('验证码发送成功!')
            this.startCountDown()
          } else {
            this.code.status = 0
            this.$message.error(response.data.message)
            console.error(response.data.message)
          }
        }).catch((error) => {
          this.code.status = 0
          this.processing = false
          this.$message.error(error)
          console.error(error)
        })
      } else {
        this.$alert('邮箱格式错误!', '提示', {
          confirmButtonText: '关闭',
          type: 'info',
          callback: action => {
          }
        })
      }
    },
    startCountDown () {
      // 假设点击获取验证码后，发送验证码请求，请求成功后执行以下代码
      // 启动倒计时
      this.code.countDown = 60
      this.code.timer = setInterval(() => {
        if (this.code.countDown > 0) {
          this.code.countDown--
        } else {
          this.code.status = 0
          clearInterval(this.code.timer)
        }
      }, 1000)
    }
  },
  computed: {
    unreadMsgSum () {
      return this.$store.state.unreadMsgSum
    },
    momentMsgSum () {
      return this.$store.state.momentMsgSum
    },
    selectedItem () {
      return this.$store.state.selectedItem
    },
    friendRequestMsgSum () {
      let friendRequestMsgArr = this.$store.state.friendRequestMsgArr
      let sum = 0
      for (let i = 0; i < friendRequestMsgArr.length; i++) {
        if (friendRequestMsgArr[i].read === 0) {
          sum++
        }
      }
      return sum
    }
  }
}
</script>

<style>
.iconfont{
  font-size: 25px;
  color: rgb(177, 178, 179);
}
.menu{
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 55px;
  color: white;
  background-color: #2e2e2e;
  text-align: center;
  padding-bottom: 20px;
}
.avatar{
  width: 35px;
  height: 35px;
  margin-top: 37px;
}
.menu-item{
  margin-top: 20px;
  cursor: pointer;
  z-index: 1000;
}
.menu-item:hover{
  color: white;
}
.menu-item-active{
  cursor: pointer;
  color: #07c160;
}
.container{
  position: fixed;
  top: 0;
  left: 55px;
  right: 0;
  bottom: 0;
}
</style>
